var rowpid=null
$(document).ready(function(){
	var type=$('#type').val();
	var pId=$('#pId').val();
	rowpid=pId;
	genDictSelect('scheduIntervalCode','timetype','1');
	genDictSelect('transferType','transfer_type','1');
	initForm(type,pId);
	//事件绑定
	eventBind(type,pId);
});
//初始化form表单
function initForm(type,pId){
	$('#regForm').validation();
	//初始化所属医院级拉框
	initHospitalSel(null,null,null);
}
//事件绑定
function eventBind(type,pId){
	$('#cancel').click(function(){
		BootstrapDialog.closeAll();
	})
	$('#save').on('click',saveNewPatient);
}
//查询医院
function initHospitalSel(defaultHosVal,defaultDeptsVal,defaultDocVal){
	$.getApiClient('/baseInfo/hospitals').get().done(function(data){
		if(!data.payload){
			data.payload=[];
		}
	    multipleSelectData("assign_hid",[{"id": "", "hospital_name": "请选择"}].concat(data.payload), defaultHosVal, {valueAttr:'id', displayAttr:'hospital_name'},'请选择');
		$('#assign_hid').multipleSelect({width:'100%', single: true});
		
		//医院科室下拉框联动
		$('#assign_hid').change(function(){
			var hosid=$(this).children('option:selected').val();
			initDepartmentSel(hosid,defaultDeptsVal,defaultDocVal);
		}).change();
	});
}

//初始化所属科室下拉框
function initDepartmentSel(hosId,defaultVal,defaultDocVal){
	if(hosId){
		$.getApiClient('/baseInfo/departments').setQuery({hospital_id:hosId}).get().done(function(data){
			if(!data.payload){
				data.payload=[];
			}
		    multipleSelectData("assign_did",[{"id": "", "department_name": "请选择"}].concat(data.payload), defaultVal, {valueAttr:'id', displayAttr:'department_name'},"请选择");
			$('#assign_did').multipleSelect({width:'100%', single: true});
		});
	}else{
		multipleSelectData("assign_did",[{"id": "", "department_name": "请选择"}], defaultVal, {valueAttr:'id', displayAttr:'department_name'},"请选择");
		$('#assign_did').multipleSelect({width:'100%', single: true});
		//科室医生下拉框联动
		$('#assign_did').change(function(){
			var deptId=$(this).children('option:selected').val();
		}).change();
	}
}

//转诊操作
function saveNewPatient(){
	if(!$("#tranForm").validationForm()){
		return;
	}
	$.getApiClient('/transfer/save').post($('#tranForm').collect(), function(params){
		return $.extend(params, {
			assign_did:$('#assign_did').multipleSelect('getSelects','text')[1],
			assign_hid: $('#assign_hid').multipleSelect('getSelects','text')[1],
			patient_id:rowpid,
			transfer_type:$('#transfer_type').multipleSelect('getSelects','text')[1]
		});
	}).done(function(data){
		if(data.code == "0"){
			BootstrapDialog.closeAll();
			customTimeOutDialog('信息提示','转诊申请成功',null,2000);
			pageQuery();
		}else{
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}